<!-- src/views/fincal/order/OrderDetails.vue -->
<template>
  <el-dialog :title="formTitle" :visible.sync="visible" width="70%" @close="handleClose">
    <el-form :model="orderDetails" label-width="150px" class="detail-form" :disabled="true">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="订单编号">
            <span>{{ orderDetails.orderUuid }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="始发地企业">
            <span>{{ orderDetails.startCompanyName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="目的地企业">
            <span>{{ orderDetails.desCompanyName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="目的地地址">
            <span>{{ orderDetails.desAddress }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="运输人员">
            <span>{{ orderDetails.driverName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="运输人员手机号码">
            <span>{{ orderDetails.driverPhone }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="企业基本运费金额 (元)">
            <span :class="{ 'highlight-bg': orderDetails.companyOffer !== 0 }">
              {{ formatCurrency(orderDetails.companyOffer) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="装卸费 (元)">
            <span :class="{ 'highlight-bg': orderDetails.loadUnloadFee !== 0 }">
              {{ formatCurrency(orderDetails.loadUnloadFee) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="驾驶员基本运费金额 (元)">
            <span :class="{ 'highlight-bg': orderDetails.driverOffer !== 0 }">
              {{ formatCurrency(orderDetails.driverOffer) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="驾驶员金额（运费+装卸费)(元)">
            <span :class="{ 'highlight-bg': orderDetails.needOfferToDriver !== 0 }">
              {{ formatCurrency(orderDetails.needOfferToDriver) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="已支付给驾驶员金额(元)">
            <span :class="{ 'highlight-bg': orderDetails.hasOfferToDriver !== 0 }">
              {{ formatCurrency(orderDetails.hasOfferToDriver) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="还需支付给驾驶员金额(元)">
            <span :class="{ 'highlight-bg': orderDetails.notHasOfferdToDriver !== 0 }">
              {{ formatCurrency(orderDetails.notHasOfferdToDriver) }}</span>
          </el-form-item>
        </el-col>



        <el-col :span="8">
          <el-form-item label="盈利 (元)">
            <span :class="{ 'highlight-bg': orderDetails.profit !== 0 }">
              {{ formatCurrency(orderDetails.profit) }}
            </span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="载货量 (吨)">
            <span>{{ orderDetails.cargoCapacity }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否已支付给驾驶员(装卸费+驾驶员基本运费)">
            <span :class="orderDetails.isOfferedToDriver === '1' ? 'paid' : 'not-paid'">
              {{ orderDetails.isOfferedToDriver === '1' ? '已支付' : '未支付' }}
            </span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="驾驶员单吨金额 (元)">
            <span>{{ formatCurrency(orderDetails.driverPerTonMoney) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="企业单吨金额 (元)">
            <span>{{ formatCurrency(orderDetails.companyPerTonMoney) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订单开始日期">
            <span>{{ parseTime(orderDetails.orderStartTime, '{y}-{m}-{d}') }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="订单结束日期">
            <span>{{ parseTime(orderDetails.orderEndTime, '{y}-{m}-{d}') }}</span>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="更新人">
            <span>{{ orderDetails.updatedBy || '无' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="更新时间">
            <span>{{ parseTime(orderDetails.updatedTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注">
            <span>{{ orderDetails.remark || '无' }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 附件部分 -->
    <div class="attachments-section">
      <h3>附件</h3>
      <el-table :data="attachments" style="width: 100%;" size="small">
        <el-table-column prop="url" label="文件名">
          <template slot-scope="scope">
            <el-button type="text" @click="downloadAttachment(scope.row)">
              {{ getFileName(scope.row.url) }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getOrder } from "@/api/fincal/order"; // 确保API路径正确
import axios from 'axios';

export default {
  name: "OrderDetails",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    orderId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      formTitle: "订单详情",
      orderDetails: {},
      attachments: [] // 附件列表
    };
  },
  watch: {
    visible(val) {
      if (val) {
        this.fetchOrderDetails();
      }
    },
    orderId(newId, oldId) {
      if (this.visible && newId !== oldId) {
        this.fetchOrderDetails();
      }
    }
  },
  methods: {
    /** 获取订单详细信息 */
    fetchOrderDetails() {
      getOrder(this.orderId)
        .then(response => {
          if (response.code === 200) {
            this.orderDetails = response.data;
            this.attachments = response.data.attachments || [];
          } else {
            this.$message.error("获取订单详情失败: " + response.msg);
          }
        })
        .catch(error => {
          this.$message.error("获取订单详情失败");
          console.error("获取订单详情失败:", error);
        });
    },
    /** 下载附件 */
    async downloadAttachment(file) {
      try {
        console.log("download file:", file);
        const response = await axios.post(
          `${process.env.VUE_APP_BASE_API}/file/download/minio?fileKey=${encodeURIComponent(file.url)}`,
          {},
          { responseType: 'blob' }
        );

        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;

        // 获取文件名
        let fileName = this.getFileName(file.url);
        const disposition = response.headers['content-disposition'];
        if (disposition && disposition.includes('filename=')) {
          const fileNameMatch = disposition.match(/filename="?([^"]+)"?/);
          if (fileNameMatch && fileNameMatch.length > 1) {
            fileName = fileNameMatch[1];
          }
        }

        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        link.remove();
        window.URL.revokeObjectURL(url); // 释放URL对象
      } catch (error) {
        this.$message.error("下载文件失败");
        console.error("下载文件失败:", error);
      }
    },
    /** 从附件URL中提取文件名 */
    getFileName(attUrl) {
      // 提取文件名，假设文件名在最后一个'-'后
      const lastDashIndex = attUrl.lastIndexOf("-");
      return lastDashIndex !== -1 ? attUrl.substring(lastDashIndex + 1) : attUrl;
    },
    /** 关闭弹窗时重置数据 */
    handleClose() {
      this.orderDetails = {};
      this.attachments = [];
      this.$emit("update:visible", false);
    },
    /** 时间格式化函数 */
    parseTime(time, format) {
      if (!time) return "";
      const date = new Date(time);
      const map = {
        "{y}": date.getFullYear(),
        "{m}": ("0" + (date.getMonth() + 1)).slice(-2),
        "{d}": ("0" + date.getDate()).slice(-2),
        "{h}": ("0" + date.getHours()).slice(-2),
        "{i}": ("0" + date.getMinutes()).slice(-2),
        "{s}": ("0" + date.getSeconds()).slice(-2)
      };
      return format.replace(/{y}|{m}|{d}|{h}|{i}|{s}/g, matched => map[matched]);
    },
    /** 货币格式化 */
    formatCurrency(value) {
      if (value === null || value === undefined) return "0.00";
      return parseFloat(value).toLocaleString("zh-CN", {
        style: "currency",
        currency: "CNY",
        minimumFractionDigits: 2
      }).replace("¥", "");
    }
  }
};
</script>

<style scoped>
.detail-form {
  margin-bottom: 20px;
}

.attachments-section {
  margin-top: 20px;
}

.highlight-bg {
  color: #ff0000;
  /* 红色字体 */
  background-color: #ffe6e6;
  /* 浅红色背景 */
  padding: 2px 4px;
  border-radius: 4px;
}

.paid {
  color: green;
  font-weight: bold;
}

.not-paid {
  color: red;
  font-weight: bold;
}

a {
  color: #409EFF;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}
</style>